package com.until.request;

import com.alibaba.fastjson.JSONObject;
import com.until.bulid.BuildUntil;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * @author user
 */
@Service
public class RequestUtil{
    /**
     * 功能描述:通过request来获取到json数据<br/>
     * @param request 请求数据
     * @return 返回json 数据处理
     */
    public JSONObject getParam(HttpServletRequest request){
        JSONObject jsonParam = null;
        try {
            // 获取输入流
            BufferedReader streamReader = new BufferedReader(new InputStreamReader(request.getInputStream(), StandardCharsets.UTF_8));
            // 写入数据到String builder
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = streamReader.readLine()) != null) {
                sb.append(line);
            }
            jsonParam = JSONObject.parseObject(sb.toString());
            // 直接将json信息打印出来
            System.out.println(jsonParam.toJSONString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jsonParam;
    }

    /**
     * 功能描述:通过request来获取到cookie中的json数据<br/>
     * @param request 请求数据
     * @return 返回json 数据处理
     */
    public JSONObject getCookies(HttpServletRequest request){
        Cookie[] cookies =  request.getCookies();
        JSONObject jsonParam = new JSONObject();
        if(cookies != null){
            for(Cookie cookie : cookies){
                jsonParam.put(cookie.getName(), cookie.getValue());
            }
        }
        return jsonParam;
    }

    /**
     * 返回的response cookie
     * @param response 返回response
     * @param cookie 添加的cookie
     */
    public void addCookie(HttpServletResponse response, Map<String,String> cookie){
        for (Map.Entry<String, String> entry : cookie.entrySet()) {
            Cookie newCookie = new Cookie(entry.getKey(), entry.setValue(entry.getKey()).toString());
            newCookie.setMaxAge(BuildUntil.COOKIE_SET_MAX_AGE);
            response.addCookie(newCookie);
        }
    }

}
